<template>
  <div class="profile-container">
    <div class="page-header">
      <h2 class="page-title">个人中心</h2>
      <p class="page-description">管理您的个人信息和账户设置</p>
    </div>
    
    <div class="profile-content">
      <!-- 个人信息卡片 -->
      <el-card class="profile-info-card">
        <template #header>
          <div class="card-header">
            <el-icon><User /></el-icon>
            <span>基本信息</span>
          </div>
        </template>
        
        <div class="profile-info">
          <div class="avatar-section">
            <el-avatar size="120" class="user-avatar">
              {{ userInitial }}
            </el-avatar>
            <el-button type="primary" @click="uploadAvatar" size="small" class="upload-btn">
              <el-icon><Upload /></el-icon>
              更换头像
            </el-button>
          </div>
          
          <div class="info-section">
            <div class="info-item">
              <label class="info-label">用户名</label>
              <span class="info-value">{{ currentUser.username }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">姓名</label>
              <span class="info-value">{{ currentUser.name || '未设置' }}</span>
            </div>
            <div class="info-item">
              <label class="info-label">角色</label>
              <el-tag :type="getRoleType">{{ getRoleName }}</el-tag>
            </div>
            <div class="info-item">
              <label class="info-label">上次登录</label>
              <span class="info-value">{{ lastLoginTime }}</span>
            </div>
          </div>
        </div>
      </el-card>
      
      <!-- 账户设置 -->
      <el-card class="account-settings-card">
        <template #header>
          <div class="card-header">
            <el-icon><Setting /></el-icon>
            <span>账户设置</span>
          </div>
        </template>
        
        <el-tabs v-model="activeTab" class="settings-tabs">
          <!-- 修改密码 -->
          <el-tab-pane label="修改密码" name="password">
            <el-form 
              :model="passwordForm" 
              :rules="passwordRules" 
              ref="passwordFormRef"
              class="password-form"
            >
              <el-form-item label="当前密码" prop="currentPassword">
                <el-input
                  v-model="passwordForm.currentPassword"
                  type="password"
                  placeholder="请输入当前密码"
                  show-password
                  :disabled="isUpdating"
                />
              </el-form-item>
              
              <el-form-item label="新密码" prop="newPassword">
                <el-input
                  v-model="passwordForm.newPassword"
                  type="password"
                  placeholder="请输入新密码"
                  show-password
                  :disabled="isUpdating"
                />
                <div class="form-hint">密码长度至少8位，包含字母和数字</div>
              </el-form-item>
              
              <el-form-item label="确认新密码" prop="confirmPassword">
                <el-input
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  placeholder="请再次输入新密码"
                  show-password
                  :disabled="isUpdating"
                />
              </el-form-item>
              
              <el-form-item>
                <el-button 
                  type="primary" 
                  @click="changePassword"
                  :loading="isUpdating"
                  :disabled="isUpdating"
                  class="update-btn"
                >
                  {{ isUpdating ? '更新中...' : '修改密码' }}
                </el-button>
                <el-button @click="resetPasswordForm" :disabled="isUpdating">
                  重置
                </el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          
          <!-- 通知设置 -->
          <el-tab-pane label="通知设置" name="notifications">
            <div class="notification-settings">
              <el-form :model="notificationSettings" class="notification-form">
                <el-form-item label="邮件通知">
                  <el-switch v-model="notificationSettings.emailEnabled" />
                  <div class="form-hint">接收重要安全事件的邮件通知</div>
                </el-form-item>
                
                <el-form-item label="扫描完成通知" v-if="notificationSettings.emailEnabled">
                  <el-switch v-model="notificationSettings.scanComplete" />
                </el-form-item>
                
                <el-form-item label="高危漏洞通知" v-if="notificationSettings.emailEnabled">
                  <el-switch v-model="notificationSettings.highVulnerability" />
                </el-form-item>
                
                <el-form-item label="系统消息通知">
                  <el-switch v-model="notificationSettings.systemMessages" />
                </el-form-item>
                
                <el-form-item label="自动刷新间隔">
                  <el-select v-model="notificationSettings.refreshInterval" placeholder="选择刷新间隔">
                    <el-option label="不自动刷新" value="0" />
                    <el-option label="30秒" value="30" />
                    <el-option label="1分钟" value="60" />
                    <el-option label="5分钟" value="300" />
                  </el-select>
                </el-form-item>
                
                <el-form-item>
                  <el-button 
                    type="primary" 
                    @click="saveNotificationSettings"
                    :loading="isUpdating"
                    :disabled="isUpdating"
                    class="save-btn"
                  >
                    保存设置
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
          
          <!-- 偏好设置 -->
          <el-tab-pane label="偏好设置" name="preferences">
            <div class="preference-settings">
              <el-form :model="preferences" class="preference-form">
                <el-form-item label="默认扫描深度">
                  <el-slider
                    v-model="preferences.defaultScanDepth"
                    :min="1"
                    :max="5"
                    :marks="{
                      1: '浅度',
                      3: '中度',
                      5: '深度'
                    }"
                  />
                </el-form-item>
                
                <el-form-item label="默认扫描类型">
                  <el-checkbox-group v-model="preferences.defaultScanTypes">
                    <el-checkbox label="sql_injection">SQL注入</el-checkbox>
                    <el-checkbox label="xss">跨站脚本</el-checkbox>
                    <el-checkbox label="info_leak">信息泄露</el-checkbox>
                    <el-checkbox label="csrf">CSRF攻击</el-checkbox>
                    <el-checkbox label="cmd_injection">命令注入</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                
                <el-form-item label="界面语言">
                  <el-radio-group v-model="preferences.language">
                    <el-radio label="zh-CN">简体中文</el-radio>
                    <el-radio label="en-US">English</el-radio>
                  </el-radio-group>
                </el-form-item>
                
                <el-form-item>
                  <el-button 
                    type="primary" 
                    @click="savePreferences"
                    :loading="isUpdating"
                    :disabled="isUpdating"
                    class="save-btn"
                  >
                    保存偏好
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { User, Setting, Upload } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import apiService from '../services/apiService.js'

// 响应式数据
const currentUser = ref({ username: 'admin', name: '系统管理员', role: 'admin' })
const isUpdating = ref(false)
const activeTab = ref('password')
const passwordFormRef = ref(null)

// 密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码验证规则
const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少为8位', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,}$/, 
      message: '密码必须包含字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 通知设置
const notificationSettings = reactive({
  emailEnabled: true,
  scanComplete: true,
  highVulnerability: true,
  systemMessages: true,
  refreshInterval: 60
})

// 偏好设置
const preferences = reactive({
  defaultScanDepth: 2,
  defaultScanTypes: ['sql_injection', 'xss', 'info_leak'],
  language: 'zh-CN'
})

// 计算属性
const userInitial = computed(() => {
  const name = currentUser.value.name || currentUser.value.username
  return name.charAt(0).toUpperCase()
})

const getRoleName = computed(() => {
  const roleMap = {
    admin: '系统管理员',
    user: '普通用户',
    guest: '访客'
  }
  return roleMap[currentUser.value.role] || currentUser.value.role
})

const getRoleType = computed(() => {
  const roleTypeMap = {
    admin: 'primary',
    user: 'success',
    guest: 'info'
  }
  return roleTypeMap[currentUser.value.role] || 'default'
})

const lastLoginTime = computed(() => {
  // 模拟上次登录时间
  const lastLogin = localStorage.getItem('lastLogin')
  if (lastLogin) {
    return new Date(lastLogin).toLocaleString('zh-CN')
  }
  return '未知'
})

// 方法
const changePassword = async () => {
  if (!passwordFormRef.value.validate()) {
    return
  }
  
  try {
    isUpdating.value = true
    
    // 模拟修改密码
    if (apiService.useMockData?.value) {
      // 模拟延迟
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      if (passwordForm.currentPassword === 'admin123') {
        ElMessage.success('密码修改成功，请重新登录')
        // 清除表单
        resetPasswordForm()
        // 可以在这里触发重新登录
      } else {
        throw new Error('当前密码错误')
      }
    } else {
      // 调用真实API
      await apiService.changePassword(
        passwordForm.currentPassword,
        passwordForm.newPassword
      )
      ElMessage.success('密码修改成功，请重新登录')
      resetPasswordForm()
    }
  } catch (error) {
    ElMessage.error(error.message || '修改密码失败')
  } finally {
    isUpdating.value = false
  }
}

const resetPasswordForm = () => {
  passwordForm.currentPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordFormRef.value?.resetFields()
}

const uploadAvatar = () => {
  ElMessageBox.alert(
    '头像上传功能正在开发中',
    '提示',
    {
      confirmButtonText: '确定',
      type: 'info'
    }
  )
}

const saveNotificationSettings = async () => {
  try {
    isUpdating.value = true
    
    // 保存到本地存储
    localStorage.setItem('notificationSettings', JSON.stringify(notificationSettings))
    
    ElMessage.success('通知设置保存成功')
  } catch (error) {
    ElMessage.error('保存设置失败')
  } finally {
    isUpdating.value = false
  }
}

const savePreferences = async () => {
  try {
    isUpdating.value = true
    
    // 保存到本地存储
    localStorage.setItem('preferences', JSON.stringify(preferences))
    
    ElMessage.success('偏好设置保存成功')
  } catch (error) {
    ElMessage.error('保存偏好设置失败')
  } finally {
    isUpdating.value = false
  }
}

// 加载用户数据
const loadUserData = async () => {
  try {
    // 从本地存储获取用户信息
    const storedUser = localStorage.getItem('user')
    if (storedUser) {
      currentUser.value = JSON.parse(storedUser)
    }
    
    // 加载通知设置
    const storedNotifications = localStorage.getItem('notificationSettings')
    if (storedNotifications) {
      Object.assign(notificationSettings, JSON.parse(storedNotifications))
    }
    
    // 加载偏好设置
    const storedPreferences = localStorage.getItem('preferences')
    if (storedPreferences) {
      Object.assign(preferences, JSON.parse(storedPreferences))
    }
  } catch (error) {
    console.error('加载用户数据失败:', error)
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadUserData()
})
</script>

<style scoped>
.profile-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 140px);
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-description {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.profile-content {
  display: grid;
  grid-template-columns: 1fr;
  gap: 24px;
}

.profile-info-card,
.account-settings-card {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s ease;
}

.profile-info-card:hover,
.account-settings-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #374151;
}

.profile-info {
  display: flex;
  align-items: center;
  gap: 40px;
  padding: 24px 0;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.user-avatar {
  font-size: 48px;
  background: linear-gradient(135deg, #409eff 0%, #2979ff 100%);
  color: white;
  border: 4px solid #ffffff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.upload-btn {
  border-radius: 6px;
  padding: 6px 16px;
}

.info-section {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.info-label {
  font-size: 14px;
  font-weight: 500;
  color: #6b7280;
}

.info-value {
  font-size: 16px;
  color: #1f2937;
  font-weight: 500;
}

.settings-tabs {
  margin-top: 16px;
}

.password-form,
.notification-form,
.preference-form {
  max-width: 600px;
}

.form-hint {
  font-size: 12px;
  color: #9ca3af;
  margin-top: 4px;
}

.update-btn,
.save-btn {
  border-radius: 6px;
  padding: 8px 24px;
}

.notification-settings,
.preference-settings {
  padding: 8px 0;
}

:deep(.el-form-item) {
  margin-bottom: 24px;
}

:deep(.el-slider) {
  margin-top: 12px;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

:deep(.el-radio-group) {
  display: flex;
  gap: 24px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-container {
    padding: 16px;
  }
  
  .profile-info {
    flex-direction: column;
    text-align: center;
    gap: 24px;
  }
  
  .info-section {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .settings-tabs :deep(.el-tabs__header) {
    padding: 0 16px;
  }
  
  .settings-tabs :deep(.el-tabs__content) {
    padding: 0 16px;
  }
  
  :deep(.el-checkbox-group),
  :deep(.el-radio-group) {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 20px;
  }
  
  .account-settings-card :deep(.el-form-item__label) {
    width: 100%;
    margin-bottom: 8px;
  }
  
  .account-settings-card :deep(.el-form-item__content) {
    margin-left: 0 !important;
  }
}
</style>